from contextlib import asynccontextmanager
from fastapi import FastAPI

from . import settings, db_manager, get_logger, db_log_handler

# 获取日志记录器
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用程序生命周期管理
    在应用启动时初始化数据库连接，关闭时清理资源
    """
    # 启动时执行
    logger.info("应用程序启动中", app_name=settings.app_name, debug_mode=settings.debug)

    try:
        # 初始化数据库连接
        await db_manager.initialize()
        # 启动数据库心跳任务
        await db_manager._start_heartbeat()

        db_log_handler.log_connection_success(
            host=settings.postgres_host,
            port=settings.postgres_port,
            database=settings.postgres_db,
            user=settings.postgres_user,
        )

        logger.info("应用程序启动完成")

    except Exception as e:
        db_log_handler.log_connection_error(
            e,
            host=settings.postgres_host,
            port=settings.postgres_port,
            database=settings.postgres_db,
            user=settings.postgres_user,
        )
        logger.error("应用程序启动失败", error=str(e))
        raise

    yield

    # 关闭时执行
    logger.info("应用程序关闭中")
    await db_manager.close()
    logger.info("应用程序已关闭")
